<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    :title="isEdit ? '编辑礼物' : '新增礼物'"
    width="60%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="gift-form"
    >
      <!-- 基本信息 -->
      <el-card class="mb-20">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12" v-if="isEdit">
            <el-form-item label="礼物ID" prop="id">
              <el-input
                v-model="formData.id"
                placeholder="请输入礼物ID（最少24位16进制字符）"
                :disabled="isEdit"
                maxlength="50"
                show-word-limit
              />
              <div class="form-tip" v-if="!isEdit">
                <el-icon><InfoFilled /></el-icon>
                <span>格式要求：最少24位，只能包含0-9、a-f、A-F字符</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中文名称" prop="name.zh">
              <el-input
                v-model="formData.name.zh"
                placeholder="请输入中文名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="英文名称" prop="name.en">
              <el-input
                v-model="formData.name.en"
                placeholder="请输入英文名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阿语名称" prop="name.ar">
              <el-input
                v-model="formData.name.ar"
                placeholder="请输入阿语名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="礼物类型" prop="giftType">
              <el-select
                v-model="formData.giftType"
                placeholder="请选择礼物类型"
                style="width: 100%"
              >
                <el-option label="普通礼物" value="ORDINARY" />
                <el-option label="幸运礼物" value="LUCKY" />
                <el-option label="国家礼物" value="NATIONAL" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格(金币)" prop="coin">
              <el-input-number
                v-model="formData.coin"
                :min="0"
                :max="99999999"
                placeholder="请输入价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="formData.sort"
                :min="0"
                :max="999"
                placeholder="请输入排序"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架状态" prop="enable">
              <el-switch
                v-model="formData.enable"
                active-text="已上架"
                inactive-text="未上架"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 图片和动效 -->
      <el-card class="mb-20">
        <template #header>
          <div class="card-header">
            <span>图片和动效</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="礼物图片" prop="previewImageUrl">
              <el-input
                disabled
                v-model="formData.previewImageUrl"
                placeholder="请输入图片URL（必须以http://或https://开头）"
              />
              <div class="upload-container" style="width: 100%; display: flex">
                <div class="form-tip">
                  <el-icon><InfoFilled /></el-icon>
                  <span>格式要求：必须以http://或https://开头的完整链接</span>
                </div>
                <div class="content-left">
                  <Upload
                    :showFileList="false"
                    :ossDir="OSS_DIR.GIFT"
                    accept=".jpg,.jpeg,.png"
                    buttonText="上传礼物"
                    @upload-success="handleUploadSuccess"
                  />
                </div>
              </div>

              <div class="image-preview" v-if="formData.previewImageUrl">
                <el-image
                  :src="formData.previewImageUrl"
                  :preview-src-list="[formData.previewImageUrl]"
                  fit="cover"
                  style="width: 100px; height: 100px; margin-top: 10px"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="动效文件" prop="animationImageUrl">
              <el-input
                disabled
                v-model="formData.animationImageUrl"
                placeholder="请输入动效文件URL（必须以http://或https://开头）"
              />

              <div class="upload-container" style="width: 100%; display: flex">
                <div class="form-tip">
                  <el-icon><InfoFilled /></el-icon>
                  <span>格式要求：必须以http://或https://开头的完整链接</span>
                </div>
                <div class="form-tip content-left">
                  <Upload
                    :showFileList="false"
                    :ossDir="OSS_DIR.GIFT"
                    accept=".webp,.mp4,.vap,.svga,.pag,.gif,.apng"
                    buttonText="上传动效"
                    @upload-success="handleUploadSuccessAnimation"
                  />
                </div>
              </div>

              <div class="animation-preview" v-if="formData.animationImageUrl">
                <el-tag type="info" style="margin-top: 10px">
                  SVGA动效文件
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 描述信息 -->
      <el-card class="mb-20">
        <template #header>
          <div class="card-header">
            <span>描述信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="中文描述" prop="desc.zh">
              <el-input
                v-model="formData.desc.zh"
                type="textarea"
                :rows="3"
                placeholder="请输入中文描述"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文描述" prop="desc.en">
              <el-input
                v-model="formData.desc.en"
                type="textarea"
                :rows="3"
                placeholder="请输入英文描述"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="阿语描述" prop="desc.ar">
              <el-input
                v-model="formData.desc.ar"
                type="textarea"
                :rows="3"
                placeholder="请输入阿语描述"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="label">
              <el-select
                v-model="formData.label"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入标签"
                style="width: 100%"
              >
                <el-option label="热门" value="热门" />
                <el-option label="新品" value="新品" />
                <el-option label="限时" value="限时" />
                <el-option label="推荐" value="推荐" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
        >
          {{ isEdit ? "保存" : "新增" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { InfoFilled } from "@element-plus/icons-vue";
import Upload from "@/components/upload/OssUpload.vue";
import { OSS_DIR } from "@/api/oss";

// 定义props
interface Props {
  modelValue: boolean;
  giftData?: any;
  isEdit?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  giftData: null,
  isEdit: false,
});

// 定义emits
const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  submit: [data: any];
}>();

// 表单ref
const formRef = ref<FormInstance>();

// 提交loading
const submitLoading = ref(false);

// 弹框显示状态
const visible = ref(false);

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      nextTick(() => {
        initFormData();
      });
    }
  }
);

// 监听visible变化
watch(visible, (newVal) => {
  emit("update:modelValue", newVal);
});

// 表单数据
const formData = reactive({
  id: "",
  name: {
    zh: "",
    en: "",
    ar: "",
  },
  giftType: "",
  coin: 0,
  sort: 1,
  enable: false,
  previewImageUrl: "",
  animationImageUrl: "",
  desc: {
    zh: "",
    en: "",
    ar: "",
  },
  label: [],
});

// 表单验证规则
const formRules: FormRules = {
  id: [
    { required: true, message: "请输入礼物ID", trigger: "blur" },
    { min: 24, message: "礼物ID最少需要24个字符", trigger: "blur" },
    {
      pattern: /^[0-9a-fA-F]+$/,
      message: "礼物ID只能包含16进制字符(0-9, a-f, A-F)",
      trigger: "blur",
    },
  ],
  "name.zh": [{ required: true, message: "请输入中文名称", trigger: "blur" }],
  "name.en": [{ required: true, message: "请输入英文名称", trigger: "blur" }],
  "name.ar": [{ required: true, message: "请输入阿语名称", trigger: "blur" }],
  giftType: [{ required: true, message: "请选择礼物类型", trigger: "change" }],
  coin: [
    { required: true, message: "请输入价格", trigger: "blur" },
    { type: "number", min: 0, message: "价格不能小于0", trigger: "blur" },
  ],
  sort: [
    { required: true, message: "请输入排序", trigger: "blur" },
    { type: "number", min: 0, message: "排序不能小于0", trigger: "blur" },
  ],
  previewImageUrl: [
    { required: true, message: "请输入图片URL", trigger: "blur" },
    {
      pattern: /^https?:\/\/.+/i,
      message: "请输入有效的HTTP/HTTPS链接",
      trigger: "blur",
    },
  ],
  animationImageUrl: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && value.trim() !== "") {
          if (!/^https?:\/\/.+/i.test(value)) {
            callback(new Error("请输入有效的HTTP/HTTPS链接"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 初始化表单数据
const initFormData = () => {
  if (props.isEdit && props.giftData) {
    // 编辑模式，填充现有数据
    Object.assign(formData, {
      id: props.giftData.id,
      name: { ...props.giftData.name },
      giftType: props.giftData.giftType,
      coin: props.giftData.coin,
      sort: props.giftData.sort,
      enable: props.giftData.enable,
      previewImageUrl: props.giftData.previewImageUrl,
      animationImageUrl: props.giftData.animationImageUrl,
      desc: { ...props.giftData.desc },
      label: [...(props.giftData.label || [])],
    });
  } else {
    // 新增模式，重置表单
    Object.assign(formData, {
      id: "",
      name: { zh: "", en: "", ar: "" },
      giftType: "",
      coin: 0,
      sort: 1,
      enable: false,
      previewImageUrl: "",
      animationImageUrl: "",
      desc: { zh: "", en: "", ar: "" },
      label: [],
    });
  }
};

// 关闭弹框
const handleClose = () => {
  visible.value = false;
  // 编辑时不清空ID字段
  if (props.isEdit) {
    formRef.value?.clearValidate();
  } else {
    formRef.value?.resetFields();
  }
};

// 上传成功，保存到表单变量
const handleUploadSuccess = (file: any) => {
  formData.previewImageUrl = file;
};
const handleUploadSuccessAnimation = (file: any) => {
  formData.animationImageUrl = file;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    console.log("开始表单验证，编辑模式:", props.isEdit);

    // 使用 Promise 方式验证表单
    const validateForm = () => {
      return new Promise((resolve, reject) => {
        // 编辑时跳过ID字段验证
        if (props.isEdit) {
          const rules = { ...formRules };
          delete rules.id;
          console.log("编辑模式验证规则:", rules);
          formRef.value?.validate((valid: boolean, fields: any) => {
            if (valid) {
              resolve(true);
            } else {
              reject(fields);
            }
          }, rules);
        } else {
          console.log("新增模式验证规则:", formRules);
          formRef.value?.validate((valid: boolean, fields: any) => {
            if (valid) {
              resolve(true);
            } else {
              reject(fields);
            }
          });
        }
      });
    };

    await validateForm();

    console.log("表单验证通过，开始提交");
    submitLoading.value = true;

    // 构建提交数据
    const submitData = {
      ...formData,
    };

    console.log("提交数据:", submitData);

    // 触发父组件的submit事件
    emit("submit", submitData);
  } catch (error) {
    console.error("表单验证失败:", error);
    ElMessage.error("表单验证失败，请检查输入");
    return; // 验证失败时直接返回，不继续执行
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
.gift-form {
  .mb-20 {
    margin-bottom: 20px;
  }

  .card-header {
    font-weight: 500;
    color: #333;
  }

  .image-preview {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    background-color: #f5f7fa;
  }

  .animation-preview {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    background-color: #f5f7fa;
  }

  .upload-container {
    width: 100%;
    margin-top: 10px;
  }

  .form-tip {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-top: 4px;
    font-size: 12px;
    color: #909399;

    .el-icon {
      font-size: 14px;
      color: #409eff;
    }
  }

  .content-left {
    margin-left: 15px;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
